<!-- 2024/11/27 生产管理-生产工单-成品改制 按钮弹框 -->
<template>
  <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body @close="cancel">
    <div v-show="stepIndex == 0">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="工单编号" prop="workorderCode">
          <el-input v-model="queryParams.workorderCode" placeholder="请输入工单编号" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <!-- add begin by zyj 2024/10/18 -->
        <el-form-item label="工单类型" prop="orderType">
          <el-select v-model="queryParams.orderType" placeholder="请选择工单类型" clearable @keyup.enter.native="handleQuery">
            <el-option v-for="item, index in dict.type.mes_order_type" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- add end by zyj 2024/10/18 -->
        <el-form-item label="流程状态" prop="workflowStatus">
          <el-select v-model="queryParams.workflowStatus" placeholder="请选择流程状态" clearable>
            <el-option v-for="dict in dict.type.workflow_status" :key="dict.value" :label="dict.label"
              :value="Number(dict.value)"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="产品编号" prop="productCode">
          <el-input v-model="queryParams.productCode" placeholder="请输入产品编号" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-select filterable clearable placeholder="请输入产品名称" v-model="queryParams.productName"
            @keyup.enter.native="handleQuery" remote @clear="onClearProductName" :loading="productNameListLoading"
            :remote-method="remoteGetProductNameList">
            <el-option v-for="(item, index) in productNameList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
          <!-- edit end by zyj 2024/10/17 产品名称支持模糊搜索下拉-->
        </el-form-item>
        <el-form-item label="单据日期" prop="fDate">
          <el-date-picker clearable v-model="queryParams.fDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择需求日期"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="workorderList" row-key="workorderId" default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" height="calc(100vh - 310px)"
        @current-change="handleCurrentChange">
        <el-table-column type="radio" width="55">
          <template slot-scope="scope">
            <el-radio :label="scope.row.workorderId" v-model="selectedId"
              @change.native="handleCurrentChange(scope.row)">{{ '' }}</el-radio>
          </template>
        </el-table-column>
        <el-table-column label="序号" align="center" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="生产工单id" align="center" prop="workorderId" width="110"></el-table-column>
        <el-table-column label="工单编号" align="center" prop="billNo" width="110"></el-table-column>
        <el-table-column label="单据日期" align="center" prop="fDate" width="160"></el-table-column>
        <el-table-column label="类型" align="center" prop="orderType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_order_type" :value="scope.row.orderType" />
          </template>
        </el-table-column>
        <el-table-column label="工单状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_workorder_status" :value="scope.row.status" />
          </template>
        </el-table-column>

        <el-table-column label="流程状态" align="center" prop="workflowStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.workflow_status" :value="scope.row.workflowStatus" />
          </template>
        </el-table-column>
        <el-table-column label="物料编码" width="150" align="center" prop="productCode" />
        <el-table-column label="物料名称" width="180" align="center" prop="productName" :show-overflow-tooltip="true" />
        <el-table-column label="规格型号" width="220" align="center" prop="productSpc" :show-overflow-tooltip="true" />
        <el-table-column label="单位" align="center" prop="unitName" />
        <el-table-column label="工单数量" align="center" prop="quantity" />
        <el-table-column label="已生产数量" align="center" width="100px" prop="quantityProduced" />
        <el-table-column label="批次号" align="center" min-width="220px">
          <template slot-scope="scope">
            <span v-if="scope.row.batchName != null">{{
              scope.row.batchName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="领料状态" align="center" width="100px">
          <template slot-scope="scope">
            <span>
              {{
                scope.row.isIssue == "0"
                  ? "未领料"
                  : scope.row.isIssue == "1"
                    ? "全部领料"
                    : scope.row.isIssue == "2"
                      ? "部分领料"
                      : "--"
              }}
            </span>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        :page-sizes="[50, 100, 200, 300, 400, 500]" @pagination="getList" />

    </div>
    <div v-show="stepIndex == 1">
      <div>
        <div class="sn-title">原工单
          <el-checkbox :indeterminate="isIndeterminateOldSN" v-model="checkedOldSNAll"
            @change="handleCheckAllOldSNChange">全选</el-checkbox>
        </div>
        <el-checkbox-group v-model="checkedOldSN" @change="handleCheckedOldSNChange">
          <el-checkbox v-for="item in oldWorkorderSNList" :label="item.label" :key="item.value">{{ item.label
            }}</el-checkbox>
        </el-checkbox-group>
      </div>
      <div>
        <div class="sn-title">改制工单
          <el-checkbox :indeterminate="isIndeterminateRemakeSN" v-model="checkedRemakeSNAll"
            @change="handleCheckAllRemakeSNChange">全选</el-checkbox>
        </div>
        <el-checkbox-group v-model="checkedRemakeSN" @change="handleCheckedRemakeSNChange">
          <el-checkbox v-for="item in remakeWorkorderSNList" :label="item.label" :key="item.value">{{ item.label
            }}</el-checkbox>
        </el-checkbox-group>
      </div>
      <div class="sn-title">改制明细</div>
      <el-table :data="dataList">
        <el-table-column label="原工单SN码" width="150" align="center" prop="oldSnCode" />
        <el-table-column label="改制工单SN码" width="150" align="center" prop="remakeSnCode" />
      </el-table>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button @click="stepIndex = 0" v-if="stepIndex == 1">上一步</el-button>
      <el-button type="primary" @click="nextStep" v-if="stepIndex == 0">下一步</el-button>
      <el-button type="primary" @click="submitForm" :loading="submitLoading" v-if="stepIndex == 1">确 定</el-button>

    </div>
  </el-dialog>
</template>

<script>
import {
  listWorkorder,
  getProductNameList,
  workorderSnList,
  remake, queryOldWorkorderCode
} from "@/api/mes/pro/workorder";
export default {
  name: "finishedProductReform",
  dicts: [
    "mes_workorder_status",
    "mes_order_status",
    "mes_order_type",
    "mes_workorder_sourcetype",
    "mes_workorder_runStatus",
    "mes_route_status",
    "workflow_status",
  ],
  data() {
    return {
      title: "成品改制明细",
      open: false,
      rowInfo: {},
      stepIndex: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        workorderCode: null,
        workorderId: null,
        workorderName: null,
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        requestDate: null,
        parentId: null,
        ancestors: null,
        //add begin by zyj 2024/10/17 查询条件增加类型
        orderType: null,
        //add end by zyj 2024/10/17 查询条件增加类型
        status: null,
        workflowStatus: null,
        fDate: null,
      },
      // 显示搜索条件
      showSearch: true,
      //add begin by zyj 2024/10/17 产品名称支持模糊搜索下拉
      productNameList: [],
      //add end by zyj 2024/10/17 产品名称支持模糊搜索下拉
      productNameListLoading: false,
      // 生产工单表格数据
      loading: true,
      total: 0,
      workorderList: [],
      selectedId: null,
      currentRow: {},
      // 生产工单表格数据  end
      oldWorkorderSNList: [], //原工单SN list
      remakeWorkorderSNList: [],////改制工单SN list
      checkedRemakeSNAll: false,
      checkedRemakeSN: [],
      isIndeterminateRemakeSN: false,
      checkedOldSNAll: false,
      checkedOldSN: [],
      isIndeterminateOldSN: false,
      dataList: [],
      submitLoading: false,
    };
  },
  watch: {
    'checkedRemakeSN': {
      handler(val) {
        this.dataList = this.mergeTwoArrIntoOneArr(this.checkedOldSN, val)
      },
      immediate: true
    },
    'checkedOldSN': {
      handler(val) {
        this.dataList = this.mergeTwoArrIntoOneArr(val, this.checkedRemakeSN)
      },
      immediate: true
    }
  },
  methods: {
    /**
     *
     * @param arr1  oldSnCode
     * @param arr2  remardkSnCode 改制
     */
    mergeTwoArrIntoOneArr(arr1, arr2) {
      let arr = [];
      if (arr1.length > arr2.length) {
        arr = arr1.map((item, index) => { return { oldSnCode: item, remakeSnCode: arr2[index] ? arr2[index] : '' } })
      } else {
        arr = arr2.map((item, index) => { return { oldSnCode: arr1[index] ? arr1[index] : '', remakeSnCode: item } })
      }
      return arr;
    },
    //初始化函数
    init(row) {
      this.rowInfo = row
      // this.queryParams.workorderId = this.rowInfo.workorderId
      // this.queryParams.workorderCode = this.rowInfo.workorderCode
      this.open = true;
      this.getList();
    },
    //add begin by zyj 2024/10/17 产品名称支持模糊搜索下拉
    onClearProductName() {
      this.remoteGetProductNameList();
    },
    remoteGetProductNameList(productName) {
      this.productNameListLoading = true;
      getProductNameList({ productName: productName }).then(res => {
        this.productNameList = res.data;
        this.productNameListLoading = false;
      })
    },
    //add end by zyj 2024/10/17 产品名称支持模糊搜索下拉
    toWorkingRecord(row) {
      this.$refs.worktimerecord.handleAddRecord(row.workorderId);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /* 2024-12-26 djj 新增 查询原工单编号 */
    getOldWorkorderCode() {
      /*       let workorderId = this.rowInfo.workorderId
            let workorderCode = this.rowInfo.workorderCode
            if (this.queryParams.workorderId) {
              workorderId = this.queryParams.workorderId
              workorderCode = this.queryParams.workorderCode
            } */
      return queryOldWorkorderCode({ workorderId: this.rowInfo.workorderId, workorderCode: this.rowInfo.workorderCode })
    },
    /** 查询生产工单列表 */
    async getList() {
      if (!this.rowInfo['workorderId']) {
        return false
      }
      /* 2024-12-26 djj 获取查询原工单编号 */
      try {
        let res = await this.getOldWorkorderCode();
        this.queryParams.oldWorkorderCodes = res.oldWorkorderCode;
      } catch {
        this.queryParams.oldWorkorderCodes = null;
      }

      this.loading = true;
      listWorkorder({ ...this.queryParams, remakeWorkorderId: this.rowInfo.workorderId }).then((response) => {
        this.workorderList = this.handleTree(
          response.rows,
          "workorderId",
          "parentId"
        );
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /* 选择新生产工单 */
    handleCurrentChange(row) {
      if (!row) {
        this.selectedId = null
        this.currentRow = {}
        return
      }
      this.selectedId = row.workorderId
      this.currentRow = row
    },
    /* 下一步 按钮 */
    nextStep() {
      if (!this.selectedId) {
        this.$message.warning("请先选择生产工单哟！");
        return false;
      }
      this.isIndeterminateRemakeSN = false
      this.isIndeterminateOldSN = false
      this.checkedOldSNAll = false
      this.checkedRemakeSNAll = false
      this.stepIndex = 1
      this.checkedOldSN = []
      this.checkedRemakeSN = []
      this.dataList = []
      this.getNextStepInfo()
    },

    async getNextStepInfo() {
      this.remakeWorkorderSNList = await this.handleSNList(this.rowInfo.workorderId, 'remakeNew')
      this.oldWorkorderSNList = await this.handleSNList(this.selectedId, 'remakeOld')
    },
    /* 处理改制工单sn数据 */
    async handleSNList(workorderId, remakeType) {
      let arr = []
      let res = await this.doGetSNList(workorderId, remakeType)
      arr = res.rows.map((item) => {
        return {
          value: item.snCode,
          label: item.snCode,
        };
      })
      return arr

    },
    async doGetSNList(workorderId, remakeType) {
      let param = {}
      param = {
        pageNum: 1,
        pageSize: 10000,
        workorderId: workorderId,
        remakeType: remakeType
      }
      return workorderSnList({ ...param })
    },
    /* 全选原工单sn */
    handleCheckAllRemakeSNChange(val) {
      this.checkedRemakeSN = val ? this.remakeWorkorderSNList.map(item => item.value) : [];
      this.isIndeterminateRemakeSN = false;
    },
    /* 复选框原工单sn */
    handleCheckedRemakeSNChange(value) {
      let checkedCount = value.length;
      this.checkRemakeSNAll = checkedCount === this.remakeWorkorderSNList.length;
      this.isIndeterminateRemakeSN = checkedCount > 0 && checkedCount < this.remakeWorkorderSNList.length;
    },
    /* 全选改制工单sn */
    handleCheckAllOldSNChange(val) {
      console.log("val", val)
      this.checkedOldSN = val ? this.oldWorkorderSNList.map(item => item.value) : [];
      this.isIndeterminateOldSN = false;
    },
    /* 复选框改制工单sn */
    handleCheckedOldSNChange(value) {
      let checkedCount = value.length;
      this.checkedOldSNAll = checkedCount === this.oldWorkorderSNList.length;
      this.isIndeterminateOldSN = checkedCount > 0 && checkedCount < this.oldWorkorderSNList.length;
    },
    /* 取消按钮 */
    cancel() {
      this.open = false;
      this.stepIndex = 0
      this.selectedId = null
      this.currentRow = {}
    },
    /** 提交按钮 */
    submitForm() {
      if (this.checkedRemakeSN.length != this.checkedOldSN.length) {
        this.$message.warning("选择的原工单与改制工单数量不一致！")
        return
      }
      this.submitLoading = true;
      let param = {}
      param = {
        oldWorkorderId: this.selectedId,
        remakeWorkorderId: this.rowInfo.workorderId,
        dataList: this.dataList
      }
      remake({ ...param }).then((res) => {
        this.$message.success("改制成功");
        this.submitLoading = false;
        this.open = false;
      }).catch(() => {
        this.submitLoading = false;
      });
    },

  }
}
</script>
<style lang='scss' scoped>
.dialog-footer {
  padding-top: 20px;
  text-align: center;
}

.sn-title {
  background-color: #ddd;
  padding: 10px;
  box-sizing: border-box;
  margin-bottom: 10px;
}

.sn-title :deep(.el-checkbox .el-checkbox__label) {
  color: #fff !important;
}
</style>
